package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.base.adapter.BaseTabViewPagerAdapter;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserInfo;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CustomException;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.base.IMBaseActivity;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.bean.beaninterface.IFriendsEntry;
import com.blockmeta.bbs.immodule.bean.databean.CardContentBean;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.fragment.CirclesFragment;
import com.blockmeta.bbs.immodule.fragment.FriendsFragment;
import com.blockmeta.bbs.immodule.net.api.CircleDetailApi;
import com.blockmeta.bbs.immodule.net.api.GetUserInfoApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleDetailResponse;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.blockmeta.bbs.immodule.Constants.CANCHOOSE;

/**
 * @author airthor
 * @date 2019/3/6
 * 通讯录
 */

@Route(path = RouterPath.IM_AddressBookActivity_ACTIVITY)
public class AddressBookActivity extends IMBaseActivity {

    @BindView(R2.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R2.id.vp_container)
    ViewPager mVpContainer;
    @BindView(R2.id.fl_next)
    View mSendBtn;

    //    private TabLayout.TabLayoutOnPageChangeListener mPageChangeListener;
//    private TabLayout.ViewPagerOnTabSelectedListener mCurrentVpSelectedListener;
    private CirclesFragment mCirclesFragment;
    private FriendsFragment mFriendsFragment;
    private boolean mIsChoose;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_address_book, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mIsChoose = getIntent().getBooleanExtra(CANCHOOSE, false);

        List<Fragment> fragments = new ArrayList<>(4);
        mCirclesFragment = CirclesFragment.newInstance(mIsChoose, true);
        mFriendsFragment = FriendsFragment.newInstance(mIsChoose, true);
        fragments.add(mCirclesFragment);
        fragments.add(mFriendsFragment);
        List<String> title = new ArrayList<>(4);
        title.add("加入的圈子");
        title.add("我的好友");
        BaseTabViewPagerAdapter vpAdapter = new BaseTabViewPagerAdapter(getSupportFragmentManager(), fragments, title);
        mVpContainer.setAdapter(vpAdapter);

        mTabLayout.setViewPager(mVpContainer);

        if (mIsChoose) {
            mSendBtn.setVisibility(View.VISIBLE);
        } else {
            mSendBtn.setVisibility(View.GONE);
        }

    }

    @OnClick({R2.id.fl_back, R2.id.fl_next})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_next) {
            //发送名片
            if (mVpContainer.getCurrentItem() == 1) {
                sendFriendCard();
            } else {
                sendCircleCard();
            }
        } else {
        }
    }

    private void sendCircleCard() {
        final List<ICircleEntry> checkedItems = mCirclesFragment.getCheckedItems();
        if (checkedItems.size() == 0) {
            ToastUtil.show("请先选择圈子");
            return;
        }
        List<ICircleEntry> circleEntries = mCirclesFragment.getCheckedItems();
        final ICircleEntry entry = circleEntries.get(0);
        RetrofitFactory.getRetrofit().create(CircleDetailApi.class)
                .circleDetail(entry.getId(), AccountHelper.getUidInt())
                .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                .compose(RxUtil.<CircleDetailResponse>commonResult())
                .compose(this.<CircleDetailResponse>bindToLifecycle())
                .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                    @Override
                    public void onNext(CircleDetailResponse circleDetailResponse) {

                        CardContentBean cardContentBean = new CardContentBean();
                        cardContentBean.setName(circleDetailResponse.name);
                        cardContentBean.setCard_type(Params.USER_GROUP);
                        cardContentBean.setId(circleDetailResponse.id);
                        cardContentBean.setImg(circleDetailResponse.groupLogo);
                        cardContentBean.setDesc(circleDetailResponse.description);

                        String deepLink = String.format("blockmeta://im/chatgroup_detail?id=%s", circleDetailResponse.id);
                        cardContentBean.setUrl(deepLink);

                        Intent intent = new Intent();
                        intent.putExtra("content", cardContentBean.toJsonString());
                        intent.putExtra("type", ChatMessage.CUSTOM_TYPE_CARD);
                        setResult(200, intent);
                        finish();
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof CustomException) {
                            ToastUtil.show(t.getMessage());
                        }
                    }
                });
    }

    private void sendFriendCard() {
        final List<IFriendsEntry> checkedItems = mFriendsFragment.getCheckedItems();
        if (checkedItems.size() == 0) {
            ToastUtil.show("请先选择好友");
            return;
        }

        List<IFriendsEntry> friendsEntries = mFriendsFragment.getCheckedItems();
        final IFriendsEntry entry = friendsEntries.get(0);
        RetrofitFactory.getRootRetrofit().create(GetUserInfoApi.class)
                .getUserInfo(String.valueOf(entry.getUserId()))
                .compose(RxUtil.<BaseImResponse<UserInfo>>rxSchedulerHelper())
                .compose(RxUtil.<UserInfo>commonResult())
                .compose(this.<UserInfo>bindToLifecycle())
                .subscribe(new CommonSubscriber<UserInfo>(mContext) {
                    @Override
                    public void onNext(UserInfo userInfo) {
                        if(userInfo != null){
                            CardContentBean cardContentBean = new CardContentBean();
                            cardContentBean.setName(entry.getName());
                            cardContentBean.setCard_type(Params.USER_PERSON);
                            cardContentBean.setId(entry.getUserId());
                            cardContentBean.setImg(entry.getAvatar());
                                cardContentBean.setDesc(userInfo.getIndividualResume());
                            String deepLink = String.format("blockmeta://im/user?id=%s", entry.getUserId());
                            cardContentBean.setUrl(deepLink);

                            Intent intent = new Intent();
                            intent.putExtra("content", cardContentBean.toJsonString());
                            intent.putExtra("type", ChatMessage.CUSTOM_TYPE_CARD);
                            setResult(200, intent);
                            finish();
                        }
                    }
                });
    }

//    private void setUpWithViewPager() {
//        if (mPageChangeListener == null) {
//            mPageChangeListener = new TabLayout.TabLayoutOnPageChangeListener(mTabLayout);
//        }
//        mVpContainer.addOnPageChangeListener(mPageChangeListener);
//        mCurrentVpSelectedListener = new TabLayout.ViewPagerOnTabSelectedListener(mVpContainer);
//        mTabLayout.addOnTabSelectedListener(mCurrentVpSelectedListener);
//    }


    /**
     * 每当这个页面可见的时候就要去请求Socket
     * 拿到最新的好友列表，交给子Fragment去处理
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
